import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 
 * @author PUSS1401
 * 
 */
@WebServlet("/Projects")
public class servletProject extends servletBase {
	private static final long serialVersionUID = 1L;
	/**
	 * A servlet that handles choosing a project to work with. Extends servletBase.
	 * 
	 * First it is checked that an user is logged in, otherwise the user is redirected to the login page.
	 * Displays all the projects that the user is a member of. The user can then choose what project to work with. 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if (session == null) {
			response.sendRedirect("lostSession.html");
			return;
		}

		HtmlGenerator gen = new HtmlGenerator();
		if (!loggedIn(request)) {
			response.sendRedirect("LogIn");
		} else {

			String name = session.getAttribute("name").toString();
			String[] projects = db.listProjectsUser(name);

			String html = selectProjectForm(projects);
			String project = request.getParameter("project");

			response.setContentType("text/html");
			PrintWriter out = response.getWriter();

			if (project != null) {
				String role = db.getRole(name, project);
				out.print(gen.getTop(name, project, role));
				out.print(gen.getProjMenu());
				session.setAttribute("project", project);
				session.setAttribute("role", role);
			} else {
				out.print(gen.getTop(name, "", ""));
				out.print(gen.getMenu());
			}
			out.print("Please choose a project");
			out.print("</br>");
			out.print(html);
			out.print(gen.getBot());
			out.close();
		}
	}

	/**
	 * Creates a html-string listing all projects that the user is a member of.
	 * @param projects
	 * 			An array of strings, containing the names of the projects that the user is a member of
	 * @return The list of the projects
	 */
	private String selectProjectForm(String [] projects) {

		String html = "<form name=" + formElement("radio");
		html += " method=" + formElement("get") + "> ";

		for (int i = 0; i < projects.length; i++) {
			if (db.activeProject(projects[i])) {
				html += " <input type=\"radio\" name=" + formElement("project")
						+ " value= \"" + projects[i] + "\" > "
						+ projects[i].toUpperCase() + " <br>";
			}
		}
		html += " <br> <input type=" + formElement("submit");
		html += " value=\"Select project\">";
		html += " </form>";
		return html;
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}